package home.projects.misc;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class LinkedListTest {

    public static void main(final String[] args) {
        testNormal();
        testEmpty();
        testNull();
    }

    private static void testNormal() {
        List<Integer> list = new ArrayList<Integer>();
        list.add(10);   list.add(20);  list.add(30);  list.add(40);
        NodeList<Integer> nodeList = new NodeList<Integer>();
        nodeList.add(1);
        nodeList.addAll(2, list);
        System.out.println(nodeList);
    }

    private static void testNull() {
        NodeList<Integer> nodeList = new NodeList<Integer>();
        nodeList.add(1);
        nodeList.addAll(2, null);
        System.out.println(nodeList);
    }

    private static void testEmpty() {
        List<Integer> list = new ArrayList<Integer>();
        NodeList<Integer> nodeList = new NodeList<Integer>();
        nodeList.add(1);
        nodeList.addAll(2, list);
        System.out.println(nodeList);
    }

}

class NodeList<E> extends LinkedList<E> {

    private static final long serialVersionUID = 1L;

    public boolean addAll(final int startIdx, final Collection<? extends E> collection) {
        if (collection == null || collection.isEmpty()) {
            return false;
        }

        final int size = collection.size();
        if (startIdx < 0 || startIdx > size - 1) {
            throw new IndexOutOfBoundsException(
                    "An out of bounds index specified: " + startIdx);
        }

        int i = 0;
        boolean collectionChanged = false;
        for (Iterator<? extends E> iter = collection.iterator(); iter.hasNext(); ++i) {
            E elem = iter.next();
            if (i >= startIdx) {
                collectionChanged = true;
                add(elem);
            }
        }
        return collectionChanged;
    }

}